"use client";
import { useState, useRef, useMemo } from "react";
import Link from "next/link";
import { useRouter } from 'next/navigation';
import { useSearchParams } from 'next/navigation';
import { Suspense } from 'react';
import { API_CONFIG } from "../../../url";

import { Alert } from "@/components/ui/alert";
//哈哈哈
interface FormData {
    id: string;
    stuName: string;
    stuIdnumber: string;
    workplace: string;
    stuPhone: string;
    teacher: string;
    photo: string;
    endDate: string;
    startDate: string;
    place: string;
    institution: string;
    jiaocai: string;
    application: string;
    payment: string;
    region: string;
    city: string;
    email: string;
    payChannel: string;
    weixin: string;
}

interface FormErrors {
    stuName: boolean;
    stuIdnumber: boolean;
    workplace: boolean;
    stuPhone: boolean;
    teacher: boolean;
    region: boolean;
    city: boolean;
    weixin: boolean;
}

function FormContent() {
    const provinces = [
        "乌鲁木齐市", "克拉玛依市", "吐鲁番市", "哈密市",
        "阿克苏地区", "喀什地区", "和田地区", "塔城地区", "阿勒泰地区",
        "昌吉回族自治州", "博尔塔拉蒙古自治州", "巴音郭楞蒙古自治州",
        "克孜勒苏柯尔克孜自治州", "伊犁哈萨克自治州"
       
    ];

    const router = useRouter();
    const searchParams = useSearchParams();
    const [isLoading, setIsLoading] = useState(true);
    const [showLoginModal, setShowLoginModal] = useState(false);
    const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string | null>(null);
    const [previewImage, setPreviewImage] = useState<string | null>(null);
    const [fileError, setFileError] = useState<string>("");
    const [showModal, setShowModal] = useState(false);
    const [modalMessage, setModalMessage] = useState("");
    const [isPaying, setIsPaying] = useState(false);
    const fileInputRef = useRef<HTMLInputElement>(null);
    const [showPaymentModal, setShowPaymentModal] = useState(false);
    const paymentQRCode = "/shoukuanma.jpg";
    const [countdown, setCountdown] = useState(0);
    const [verificationCode, setVerificationCode] = useState("");

    const [userId, setUserId] = useState<string | null>(null);
    const token = localStorage.getItem('token');

    const showErrorModal = (message: string) => {
        setModalMessage(message);
        setShowModal(true);
    };

    const closeModal = () => {
        setShowModal(false);
        setModalMessage("");
    };

    const triggerFileInput = () => {
        fileInputRef.current?.click();
    };

    const clearFileInput = (e: React.MouseEvent) => {
        e.stopPropagation();
        setPreviewImage(null);
        setFileError("");
        if (fileInputRef.current) fileInputRef.current.value = "";
    };

    // const userId = localStorage.getItem('userId');
    // 初始化表单数据
    const [formData, setFormData] = useState<FormData>({
        id: "userId",
        stuName: "",
        stuIdnumber: "",
        workplace: "",
        stuPhone: "",
        teacher: "",
        photo: "",
        endDate: "",
        startDate: "",
        place: "",
        institution: "",
        jiaocai: "",
        application: "",
        payment: "",
        region: "新疆维吾尔自治区",
        city: "",
        email: "",
        payChannel: "",
        weixin: "",
    });

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
        const { id, value } = e.target;
        setFormData(prev => ({ ...prev, [id]: value }));
    };

    // 使用派生状态替代实时验证
    const formErrors = useMemo(() => ({
        stuName: formData.stuName.trim() === "",
        stuIdnumber: formData.stuIdnumber.trim() === "",
        workplace: formData.workplace.trim() === "",
        stuPhone: formData.stuPhone.trim() === "",
        teacher: formData.teacher.trim() === "",
        region: formData.region.trim() === "",
        city: formData.city.trim() === "",
        weixin: formData.weixin.trim() === "",
    }), [formData]);

    // 表单是否有效的计算
    const isFormValid = useMemo(() =>
        !Object.values(formErrors).some(error => error),
        [formErrors]
    );

    // 只在提交时使用的验证函数
    const validateForm = () => {
        return isFormValid;
    };

    // 实际提交数据的函数
    const submitFormData = async (paymentMethod: string) => {
        try {
            const response = await fetch(`${API_CONFIG.BASE_URL}/api/student/add`, {
            //     const response = await fetch('http://192.168.1.173:8080/student/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
                credentials: 'include',
                body: JSON.stringify({
                    ...formData,
                    id: userId, // 添加 userId 到请求体
                    payChannel: formData.payChannel,
                    action: "save",
                    photoBase64: formData.photo.split(',')[1]
                }),
            });

            if (!response.ok) {
                throw new Error('网络响应异常');
            }

            const result = await response.json();
            showErrorModal('报名成功！');
            console.log('操作成功:', result);
        } catch (error) {
            const message = error instanceof Error ? error.message : '操作失败，请重试';
            showErrorModal(message);
            console.error('操作出错:', error);
        } finally {
            setIsPaying(false);
        }
    };

    // 发送验证码
    const sendVerificationCode = async () => {
        if (!formData.stuPhone) {
            showErrorModal("请输入手机号码");
            return;
        }

        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(formData.stuPhone)) {
            showErrorModal("请输入正确的手机号码");
            return;
        }

        try {
            setCountdown(60);
            const timer = setInterval(() => {
                setCountdown((prev) => {
                    if (prev <= 1) clearInterval(timer);
                    return prev - 1;
                });
            }, 1000);

            const response = await fetch(`${API_CONFIG.BASE_URL}/api/sms/send`, {
           //     const response = await fetch('http://192.168.1.173:8080/sms/send', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
                credentials: 'include',

                body: JSON.stringify({
                    phone: formData.stuPhone,
                    type: "register"
                }),
            });

            if (!response.ok) {
                throw new Error('发送验证码失败');
            }

            showErrorModal("验证码已发送");
        } catch (error) {
            showErrorModal("发送验证码失败，请重试");
        }
    };

    const handleSave = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!validateForm()) {
            showErrorModal("请填写所有必填字段");
            return;
        }

        setIsPaying(true);
        try {
            // const token = localStorage.getItem('token');
           const response = await fetch(`${API_CONFIG.BASE_URL}/api/student/add`, {
            //     const response = await fetch('http://192.168.1.173:8080/student/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
                credentials: 'include',

                body: JSON.stringify({
                    ...formData,
                    id: userId, // 添加 userId 到请求体
                    action: "save",
                    photoBase64: formData.photo.split(',')[1]
                }),
            });

            if (!response.ok) {
                const errorResult = await response.json();
                showErrorModal(errorResult.message || '报名失败');
                return;
            }

            const result = await response.json();
            setShowModal(true);
            setModalMessage("报名成功！请点击“去支付”完成付款。");
        } catch (error) {
            showErrorModal((error as Error).message || '报名失败');
        } finally {
            setIsPaying(false);
        }
    };

    // 添加错误样式类
    const getInputClass = (fieldName: keyof FormErrors) => {
        return `flex-grow px-4 py-2 border rounded-md ${formErrors[fieldName] ? "border-red-500 bg-red-50" : "border-gray-300"}`;
    };

    // 修改支付相关状态
    const [paymentInfo, setPaymentInfo] = useState<{
        qrCode?: string;
        orderNo?: string;
        amount?: number;
    }>({});

    // 重构的提交处理函数
    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!validateForm()) {
            showErrorModal("请填写所有必填字段");
            return;
        }

        setIsPaying(true);
        try {
            const response = await fetch(`${API_CONFIG.BASE_URL}/api/student/add`, {
              //  const response = await fetch('http://192.168.1.173:8080/student/add', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
                credentials: 'include',

                body: JSON.stringify({
                    ...formData,
                    action: "save",
                    photoBase64: formData.photo.split(',')[1]
                }),
            });

            if (!response.ok) {
                const errorResult = await response.json();
                showErrorModal(errorResult.message || '请求失败');
                return;
            }

            const result = await response.json();
            if (result.qrCode) {
                setPaymentInfo({
                    qrCode: `data:image/png;base64,${result.qrCode}`,
                    orderNo: result.orderNo,
                    amount: 2298
                });
                setShowPaymentModal(true);
            }
        } catch (error) {
            showErrorModal((error as Error).message || '提交失败');
        } finally {
            setIsPaying(false);
        }
    };

    // 修改支付状态查询逻辑为单次查询
    const checkPaymentStatus = async (orderNo: string) => {
        try {
            const statusResponse = await fetch(`${API_CONFIG.BASE_URL}/api/pay/query?oderId=${orderNo}`,
          //  const statusResponse = await fetch(`http://192.168.1.173:8080/student/pay/query?oderId=${orderNo}`,
                {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    credentials: 'include',

                }
            );
            const status = await statusResponse.json();
            if (status.status === 'UNPAID') {
                setShowModal(true);
                setModalMessage(status.message || "订单未支付，请继续支付");
            } else if (status.msg === 'SUCCESS') {
                setShowModal(true);
                setModalMessage("支付成功！");
                setShowPaymentModal(false);
            } else {
                showErrorModal("系统异常请联系管理员！");
            }
        } catch (error) {
            showErrorModal("查询支付状态失败，请重试");
        }
    };

    // 添加状态变量记录上次点击时间
    const [lastPaymentClickTime, setLastPaymentClickTime] = useState<number | null>(null);

    // 添加缓存机制
    const [paymentCache, setPaymentCache] = useState<{ [key: string]: { qrCode: string; orderNo: string; amount: number } }>({});

    // 修改支付方式选择逻辑
    const handlePaymentMethodSelect = async (method: string) => {
        const currentTime = Date.now();
        const userId = localStorage.getItem('userId');
        // if (lastPaymentClickTime && (currentTime - lastPaymentClickTime) < 5 * 1 * 1000) {
        //     showErrorModal("请等待5分钟后再次尝试选择支付方式");
        //     return;
        // }

        setSelectedPaymentMethod(method);
        setFormData(prev => ({ ...prev, payChannel: method }));
        setLastPaymentClickTime(currentTime);

        try {
           const response = await fetch(`${API_CONFIG.BASE_URL}/api/pay`, {
               //   const response = await fetch('http://192.168.1.173:8080/student/pay', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
                credentials: 'include',

                body: JSON.stringify({
                    ...formData,
                    id: userId,
                    payChannel: method
                }),
            });

            if (!response.ok) {
                const errorResult = await response.json();
                showErrorModal(errorResult.message || '支付失败');
                return;
            }

            const result = await response.json();
            if (result.qrCode) {
                const newPaymentInfo = {
                    qrCode: `data:image/png;base64,${result.qrCode}`,
                    orderNo: result.orderNo,
                    amount: 2298
                };
                setPaymentInfo(newPaymentInfo);
                setShowPaymentModal(true);
            }
        } catch (error) {
            showErrorModal((error as Error).message || '支付失败');
        }
    };

    // 页面加载时检查登录状态并获取用户数据
    useState(() => {
        const checkLoginAndFetchData = async () => {
            const userId = localStorage.getItem('userId');
            const userPhone = localStorage.getItem('userPhone');
            const storedUserId = localStorage.getItem('userId');



            // 如果没有userId或token，直接显示登录弹窗
            // if (!userId || !token) {
            //     setShowLoginModal(true);
            //     setIsLoading(false);
            //     return;
            // }
            setUserId(storedUserId); // 存储 userId 到状态

            // if (!userId || !userPhone) {
            //     setShowLoginModal(true);
            //     setIsLoading(false);
            //     return;
            // }
            try {
              const response = await fetch(`${API_CONFIG.BASE_URL}/api/student/getStudentById?id=${userId}`,
                //   const response = await fetch(` http://192.168.1.173:8080/student/getStudentById?id=${userId}`,
                    {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${token}`
                        },
                        credentials: 'include',

                    }
                );
              


                // if (status.status === 'UNPAID') {
                //     setShowModal(true);
                //     setModalMessage(status.message || "订单未支付，请继续支付");
                // } else if (status.msg === 'SUCCESS') {
                //     setShowModal(true);
                //     setModalMessage("支付成功！");
                //     setShowPaymentModal(false);
                // } else {
                //     showErrorModal("系统异常请联系管理员！");
                // }

                if (response.status === 403) {
                    
                   setShowLoginModal(true);
                    return;
                   // throw new Error('获取用户信息失败');
                }
                const userData = await response.json();

                // 修改这部分代码，处理null值情况
                setFormData(prev => ({
                    ...prev,
                    stuName: userData.stuName || "",  // 如果为null则显示空字符串
                    stuIdnumber: userData.stuIdnumber || "",
                    workplace: userData.workplace || "",
                    stuPhone: userData.stuPhone || userPhone,  // 优先使用接口返回的手机号
                    teacher: userData.teacher || "",
                    city: userData.city || "",
                    email: userData.email || "",
                    weixin: userData.weixin || ""
                }));
            } catch (error) {
                console.error('获取用户信息失败:', error);
                // showErrorModal('获取用户信息失败，请重新登录');
              //  setShowLoginModal(true);
            } finally {
                setIsLoading(false);
            }
        };

        checkLoginAndFetchData();
    }, []);

    const redirectToLogin = () => {
        router.push('/login');
    };

    if (isLoading) {
        return <div className="flex justify-center items-center h-screen">加载中...</div>;
    }

    return (
        <main className="min-h-screen">
        {/* 登录提示弹窗 */}
        {showLoginModal && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div className="bg-white rounded-lg p-6 max-w-md w-full relative">
                        {/* Close button */}
                        <button
                            onClick={() => setShowLoginModal(false)}
                            className="absolute top-2 right-2 p-1 rounded-full hover:bg-gray-100"
                        >
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                className="h-6 w-6 text-gray-500"
                                fill="none"
                                viewBox="0 0 24 24"
                                stroke="currentColor"
                            >
                                <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={2}
                                    d="M6 18L18 6M6 6l12 12"
                                />
                            </svg>
                        </button>

                        <p className="mb-6 text-center">已过期请重新登录</p >

                        <div className="flex justify-center">
                            <button
                                onClick={redirectToLogin}
                                className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                            >
                                去登录
                            </button>
                        </div>
                    </div>
                </div>
            )}
            {/* 错误提示弹窗 */}
            {showModal && (
                  <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div className="bg-white rounded-lg p-6 max-w-md w-full  ">
                        <p className="mb-6">{modalMessage}</p>
                        <div className="flex justify-end space-x-4">
                            <button
                                onClick={closeModal}
                                className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
                            >
                                确定
                            </button>
                            {modalMessage.includes("报名成功！") && (
                                <button
                                    onClick={() => {
                                        setSelectedPaymentMethod(null); // 重置支付方式
                                        setPaymentInfo({}); // 清空支付信息
                                        setShowModal(false);
                                        setShowPaymentModal(true);
                                    }}
                                    className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
                                >
                                    去支付
                                </button>
                            )}
                            {modalMessage === "支付成功！" && (
                                <Link href="/invoice">
                                    <button
                                        className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
                                    >
                                        开发票
                                    </button>
                                </Link>
                            )}
                        </div>
                    </div>
                </div>
            )}

            {/* 支付弹窗 */}
            {showPaymentModal && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div className="bg-white rounded-lg p-6 max-w-md w-full border-4 border-red-500">
                        {!selectedPaymentMethod ? (
                            <div>
                                <h3 className="text-lg font-bold mb-4 text-center">请选择支付方式</h3>
                                <div className="flex justify-center space-x-4">
                                    <button
                                        onClick={() => handlePaymentMethodSelect('WX_NATIVE')}
                                        className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
                                    >
                                        微信支付
                                    </button>
                                    <button
                                        onClick={() => handlePaymentMethodSelect('ALI_QR')}
                                        className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
                                    >
                                        支付宝支付
                                    </button>
                                </div>
                                <div className="flex justify-center mt-4">
                                    <button
                                        onClick={() => setShowPaymentModal(false)}
                                        className="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300"
                                    >
                                        取消
                                    </button>
                                </div>
                            </div>
                        ) : (
                            <div>
                                <h3 className="text-lg font-bold mb-4 text-center">请完成支付</h3>
                                <div className="flex justify-center mb-4">
                                    <img
                                        src={paymentInfo.qrCode}
                                        alt="收款码"
                                        className="w-64 h-64 object-contain border border-gray-200"
                                    />
                                </div>
                                <div className="text-center mb-4">
                                    <p className="text-gray-600">请使用{selectedPaymentMethod === 'WX_NATIVE' ? '微信' : '支付宝'}扫描二维码</p>
                                    <p>手机端请长按二维码或截图保存后支付</p>
                                    <p>支付完成请"×"掉支付页面，回到报名页面</p>
                                    <p>点击已完成支付可进行开票，选择个人开票或单位开票</p>
                                    <p className="text-sm text-gray-500 mt-2">金额：教材费￥98 + 培训费￥2200</p>
                                </div>
                                <div className="flex justify-center space-x-4">
                                    <button
                                        onClick={() => setShowPaymentModal(false)}
                                        className="px-4 py-2 bg-gray-200 text-gray-800 rounded hover:bg-gray-300"
                                    >
                                        取消
                                    </button>
                                    <button
                                        onClick={() => {
                                            checkPaymentStatus(paymentInfo.orderNo || '');
                                            setShowPaymentModal(false);
                                        }}
                                        className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600"
                                    >
                                        已完成支付
                                    </button>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            )}

            <section className="py-20 pt-8">
                <div className="container mx-auto px-4 grid grid-cols-1 md:grid-cols-3 gap-8">
                    {/* border-t-2 border-b-2  border-l-2 border-r-2 border-dashed border-red-400 */}
                    <div className="bg-blue-600 rounded-lg shadow-sm p-6 hidden md:block -ml-20 mt-2  ">
                        <h3 className="text-lg font-bold text-white mb-4 ">新疆维吾尔自治区独家合作机构</h3>
                        <p className="text-sm mb-4 text-gray-700 text-white">
                            （负责在新疆维吾尔自治区内开展《网络主播合规管控》<br />
                            培训项目宣传/推广/招生/发证等）
                        </p>
                        <div className="space-y-3 text-sm text-white mb-4">
                            <p><strong>中瑞岳华税务师事务所集团有限公司</strong></p>
                            <p>社会统一信用代码：91650100726963076K</p>
                            <p>法定代表人：赵成斌</p>
                            <p>项目负责人：修玉 13579227960</p>
                            <p>地址：新疆乌鲁木齐经济技术开发区（头屯河区）喀纳斯湖北路455号软件园F1栋104室</p>
                        </div>
                        <div className="space-y-3 text-sm text-white mt-16">
                            <p className="text-center text-xl"><strong>参加网络主播合规管控培训学员需提交制证信息 </strong></p>
                            <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;制证信息包含<span className="font-bold ">电子版制证表格</span>和<span className="font-bold ">电子版照片</span>，各合作机构和学员需按要求一并提供此两项内容。对不符合要求的制证信息，中税师（北京）税务咨询中心将及时反馈予给合作机构和学员，进行补充修改，由此造成的证书制作延期由合作机构和学员负责。</p>
                            <p>（一）<span className="font-bold ">电子版制证表格</span>：用文本格式填写证书登记表，不可更改表格样式（如擅自合并单元格、添加或删除行列等），不可遗漏必要制证信息。</p>
                            <p>（二）<span className="font-bold ">电子版照片</span>：提交以本人身份证号命名（X使用大写）的格式为.JPG的个人近期免冠电子照片。建议照片尺寸为33mm（高）×23mm（宽），<span className="font-bold ">大小在20KB-150KB之间</span>，白底，确保人像清晰。</p>
                            <p>（三）以本人身份证号命名（X使用大写）的电子版照片：即在编辑电子版照片时，在照片的下方命名格内填写上本人身份证号码，然后保存提交。</p>
                            {/* <p>地址：广州市天河区华强路3号之二1309号</p> */}
                        </div>
                    </div>

                    <div className="md:col-span-2">
                        <div className="bg-white rounded-lg shadow-sm p-8">
                            <form className="space-y-6 " >
                                <div className="flex items-center" >
                                    <label htmlFor="certificate-number" className="block text-sm font-medium mb-2 mr-4">
                                        姓&emsp;&nbsp;&emsp;名<span className="text-red-600">*</span>  &emsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    </label>
                                    <input
                                        type="text"
                                        id="stuName"
                                        className="flex-grow px-4 py-2 border rounded-md"
                                        placeholder="请输入姓名"
                                        required
                                        onChange={handleInputChange} // 添加这行
                                        value={formData.stuName}    // 添加这行
                                    />
                                </div>
                                <div className="flex items-center">
                                    <label htmlFor="name" className="block text-sm font-medium mb-2 mr-4">
                                        身份证号 <span className="text-red-600">*</span>&emsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    </label>
                                    <input
                                        type="text"
                                        id="stuIdnumber"
                                        className="w-full px-4 py-2 border rounded-md peer"
                                        placeholder="请输入18位身份证号"
                                        required
                                        minLength={18}
                                        maxLength={18}
                                        pattern="\d{17}[\dXx]"
                                        onChange={handleInputChange}
                                        value={formData.stuIdnumber}
                                    />
                                </div>
                                <div className="flex items-center">
                                    <label htmlFor="name" className="block text-sm font-medium mb-2 mr-4">
                                        省&emsp;&nbsp;&emsp;份<span className="text-red-600">*</span> &emsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    </label>
                                    <input
                                        type="text"
                                        id="region"
                                        // name="region"
                                        className="flex-grow px-4 py-2 border rounded-md"
                                        placeholder="请输入工作单位"
                                        required
                                        onChange={handleInputChange} // 添加这行
                                        // value={formData.workplace}    // 添加这行
                                        value="新疆维吾尔自治区(工作省份)"  // 设置默认值
                                        readOnly           // 禁止用户输入
                                    />

                                </div>
                                <div className="flex items-center">
                                    <label htmlFor="city" className="block text-sm font-medium mb-2 mr-4">
                                        市&emsp;&nbsp;&emsp;区<span className="text-red-600">*</span> &emsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    </label>
                                    <select
                                        id="city"
                                        className="flex-grow px-4 py-2 border rounded-md"
                                        required
                                        onChange={handleInputChange}
                                        value={formData.city}
                                    >
                                        <option value="">请选择市(工作地市)</option>
                                        {provinces.map(province => (
                                            <option key={province} value={province}>
                                                {province}
                                            </option>
                                        ))}
                                    </select>
                                    {formErrors.city && (
                                        <span className="ml-2 text-sm text-red-500">请选择市</span>
                                    )}
                                </div>
                                <div className="flex items-center">
                                    <label htmlFor="name" className="block text-sm font-medium mb-2 mr-4">
                                        工作单位<span className="text-red-600">*</span> &emsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    </label>
                                    <input
                                        type="text"
                                        id="workplace"
                                        className="flex-grow px-4 py-2 border rounded-md"
                                        placeholder="请输入工作单位"
                                        required
                                        onChange={handleInputChange} // 添加这行
                                        value={formData.workplace}    // 添加这行
                                    />
                                </div>
                                <div className="flex items-center">
                                    <label htmlFor="name" className="block text-sm font-medium mb-2 mr-4">
                                        手机号码 <span className="text-red-600">*</span>&emsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    </label>
                                    <input
                                        type="text"
                                        id="stuPhone"
                                        className=" px-4 py-2 border rounded-md flex-grow"
                                        placeholder="请输入本人手机号码"
                                        required
                                        minLength={11}
                                        maxLength={11}
                                        pattern="\d{17}[\dXx]"
                                        onChange={handleInputChange} // 添加这行
                                        value={formData.stuPhone}    // 添加这行
                                    />
                                    {/* {formErrors.stuName && (
                    <span className="ml-2 text-sm text-red-500">必填</span>
                  )} */}
                                </div>
                                {/* 新增验证码输入框和发送按钮 */}
                                {/* <div className="flex items-center">
                  <label htmlFor="code" className="block text-sm font-medium mb-2 mr-4">
                    验证码 <span className="text-red-600">*</span>&emsp; &nbsp;&emsp;&emsp; &nbsp;
                  </label>
                  <div className="flex flex-grow gap-2">
                    <input
                      type="text"
                      id="code"
                      className="px-4 py-2 border rounded-md flex-1"
                      placeholder="请输入验证码"
                      required
                      onChange={handleInputChange}
                      value={formData.code}
                      maxLength={6}
                    />
                    <button
                      type="button"
                      onClick={sendVerificationCode}
                      disabled={countdown > 0}
                      className={`px-4 py-2 rounded-md ${countdown > 0
                        ? 'bg-gray-300 text-gray-500'
                        : 'bg-blue-600 text-white hover:bg-blue-700'}`}
                    >
                      {countdown > 0 ? `${countdown}秒后重发` : '获取验证码'}
                    </button>
                  </div> */}
                                {/* </div> */}
                                <div className="flex items-center">
                                    <label htmlFor="name" className="block text-sm font-medium mb-2 mr-4">
                                        招生老师<span className="text-red-600">*</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                                    </label>
                                    <input
                                        type="text"
                                        id="teacher"
                                        className=" px-4 py-2 border rounded-md flex-grow"
                                        placeholder="请输入招生老师姓名"
                                        required
                                        onChange={handleInputChange} // 添加这行
                                        value={formData.teacher}    // 添加这行
                                    />
                                </div>
                                <div className="flex items-center">
                                    <label htmlFor="certificate-number" className="block text-sm font-medium mb-2 mr-4">
                                        邮&emsp;&nbsp;&emsp;箱&nbsp;(选填)&nbsp;&nbsp;&nbsp;
                                    </label>
                                    <input
                                        type="text"
                                        id="email"
                                        className=" px-4 py-2 border rounded-md flex-grow"
                                        placeholder="请输入邮箱方便后期开票使用"
                                        required
                                        onChange={handleInputChange} // 添加这行
                                        value={formData.email}    // 添加这行
                                    />
                                </div>
                                <div className="flex items-center" >
                                    <label htmlFor="certificate-number" className="block text-sm font-medium mb-2 mr-4">
                                        微信号码<span className="text-red-600">*</span>  &emsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    </label>
                                    <input
                                        type="text"
                                        id="weixin"
                                        className="flex-grow px-4 py-2 border rounded-md"
                                        placeholder="请输入微信号码"
                                        required
                                        onChange={handleInputChange} // 添加这行
                                        value={formData.weixin}    // 添加这行
                                    />
                                </div>
                                <div className="flex">
                                    <button
                                        type="button"
                                        onClick={handleSave}
                                        className={`w-full py-2 rounded-md mr-2 ${isFormValid
                                            ? "bg-primary text-white hover:bg-primary/90"
                                            : "bg-gray-300 text-gray-500 cursor-not-allowed"
                                            }`}
                                        disabled={!isFormValid}
                                    >
                                         保存并缴费
                                    </button>
                                    <button
                                        type="button"
                                        onClick={(e) => handleSave(e)}
                                        className={`w-full py-2 rounded-md ${validateForm()
                                            ? "bg-primary text-white hover:bg-primary/90"
                                            : "bg-gray-300 text-gray-500 cursor-not-allowed"
                                            }`}
                                    >
                                        修改信息（提交）
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </section>
        </main>
    )
}

export default function CertificatesPage() {
    return (
        <Suspense fallback={<div>Loading...</div>}>
            <FormContent />
        </Suspense>
    );
}	